package com.yu.base.configuration;

import com.alibaba.fastjson.JSON;
import com.yu.base.entity.Assay;
import com.yu.base.dto.WebSocketDTO;
import com.yu.base.entity.Img;
import com.yu.base.entity.Pathology;
import com.yu.base.mapper.assay.HospitalAssayMapper;
import com.yu.base.mapper.img.HospitalImgMapper;
import com.yu.base.mapper.msg.MsgMapper;
import com.yu.base.mapper.pathology.HospitalPathologyMapper;
import com.yu.base.service.ScoketClient;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class WebSocketConfig {

    @Value("${ws.server}")
    private String server;

    @Autowired
    HospitalAssayMapper hospitalAssayMapper;

    @Autowired
    MsgMapper msgMapper;

    @Autowired
    private HospitalPathologyMapper hospitalPathologyMapper;

    @Autowired
    private HospitalImgMapper hospitalImgMapper;

    @Autowired
    private ScoketClient scoketClient;

    @Bean
    public WebSocketClient webSocketClient() {
        try {
            WebSocketClient webSocketClient = new WebSocketClient(new URI(server+"/test"),new Draft_6455()) {
                private boolean flag = false;

                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    flag = false;
                    log.info("[websocket] 连接成功");
                }
 
                @SneakyThrows
                @Override
                public void onMessage(String message) {
                    log.info("[websocket] 收到消息={}",message);
                    try {
                        WebSocketDTO dto = JSON.parseObject(message, WebSocketDTO.class);
                        //1 短信  2 化验 3 影像  4 病理
                        if("1".equals(dto.getType())){
                            msgMapper.send(dto.getPhone(),dto.getContent(),dto.getDate());
                        }else if("2".equals(dto.getType())){
                            List<Assay> assays = hospitalAssayMapper.getAssay(dto.getIdCard(), dto.getDate());
                            if(!CollectionUtils.isEmpty(assays)){
                                dto.setData(assays);
                                this.send(JSON.toJSONString(dto));
                            }
                        }else if("3".equals(dto.getType())){
                            List<String> userInfo = hospitalAssayMapper.getUserInfo(dto.getIdCard());
                            if(!CollectionUtils.isEmpty(userInfo)) {
                                StringBuilder sb = new StringBuilder();
                                for (String s : userInfo) {
                                    sb.append("'").append(s).append("'").append(",");
                                }
                                String idCards = sb.substring(0, sb.length() - 1).toString();
                                String imgDate = DateFormatUtils.format(dto.getDate(), "yyyyMMddHHmmss");
                                List<Img> imgs = hospitalImgMapper.getImg(idCards, Long.valueOf(imgDate));
                                if(!CollectionUtils.isEmpty(imgs)){
                                    dto.setData(imgs);
                                    scoketClient.send(JSON.toJSONString(dto));
                                }
                            }
                        }else if("4".equals(dto.getType())){
                            List<String> userInfo = hospitalAssayMapper.getUserInfo(dto.getIdCard());
                            if(!CollectionUtils.isEmpty(userInfo)){
                                StringBuilder sb = new StringBuilder();
                                for (String s : userInfo) {
                                    sb.append("'").append(s).append("'").append(",");
                                }
                                String idCards = sb.substring(0,sb.length()-1).toString();
                                List<Pathology> pathologys = hospitalPathologyMapper.getPathology(idCards, dto.getDate());
                                if(!CollectionUtils.isEmpty(pathologys)){
                                    dto.setData(pathologys);
                                    scoketClient.send(JSON.toJSONString(dto));
                                }
                            }
                        }
                    }catch (Exception e){
                        log.error("[websocket] 处理消息失败",message);
                    }
                }
 
                @SneakyThrows
                @Override
                public void onClose(int code, String reason, boolean remote) {
                    log.info("[websocket] 退出连接");
                }
 
                @Override
                public void onError(Exception ex) {
                    log.error("[websocket] 连接错误:",ex);
                }
            };
            webSocketClient.connect();
            return webSocketClient;
        } catch (Exception e) {
            log.error("",e);
        }
        return null;
    }
 
}